package com.sdkj.fixed.asset.hc.controller;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.sdkj.fixed.asset.api.hc.CategoryApi;
import com.sdkj.fixed.asset.api.hc.vo.in.ConsumeParams;
import com.sdkj.fixed.asset.api.hc.vo.in.MablesParams;
import com.sdkj.fixed.asset.api.hc.vo.in.StockParams;
import com.sdkj.fixed.asset.api.hc.vo.out.ReceiptCon;
import com.sdkj.fixed.asset.api.hc.vo.out.ReceiptConsume;
import com.sdkj.fixed.asset.api.hc.vo.out.ReceiptMables;
import com.sdkj.fixed.asset.api.hc.vo.out.ReceiptStock;
import com.sdkj.fixed.asset.common.base.*;
import com.sdkj.fixed.asset.common.utils.TimeTool;
import com.sdkj.fixed.asset.hc.mapper.OrgManagementMapper;
import com.sdkj.fixed.asset.hc.service.CategoryService;
import com.sdkj.fixed.asset.hc.util.CacheUtil;
import com.sdkj.fixed.asset.hc.util.ExcelStyle;
import com.sdkj.fixed.asset.hc.util.ExcelUtils;
import com.sdkj.fixed.asset.pojo.hc.Category;
import com.sdkj.fixed.asset.pojo.hc.group.AddCategory;
import com.sdkj.fixed.asset.pojo.hc.group.DelCategory;
import com.sdkj.fixed.asset.pojo.hc.group.EditCategory;
import com.sdkj.fixed.asset.pojo.hc.group.ViewCategory;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 史晨星
 * @ClassName: CategoryController
 * @Description: 仓库管理
 * @date 2020年7月20日
 */
@Validated
@RestController()
public class CategoryController extends BaseController<Category> implements CategoryApi {

    private static Logger log = LoggerFactory.getLogger(CategoryController.class);

    @Resource
    private CategoryService service;

    @Resource
    private OrgManagementMapper orgManagementMapper;

    @Resource
    private HttpServletRequest request;
    @Autowired
    private HttpServletResponse response;

    @Override
    public BaseService<Category> getService() {
        return service;
    }

    @Resource
    private CacheUtil cacheUtil;

    /**
     * 新增
     *
     * @param entity
     * @return
     */
    @Override
    public BaseResultVo add(@Validated({AddCategory.class}) Category entity) throws Exception {
        String token = request.getHeader("token");
        String userId = cacheUtil.getUser(token).getUserId();
        String orgId = cacheUtil.getUser(token).getCompanys().get(0).getCompanyId();
        entity.setCuser(userId);
        entity.setEuser(userId);
        entity.setEtime(DateUtil.now());
        entity.setCtime(DateUtil.now());
        entity.setState(1);
        entity.setIsCheck(2);
        entity.setOrgId1(orgId);
        Category category = service.add(entity);
        return BaseResultVo.success("success", category.getId());
    }

    /**
     * 修改
     *
     * @param entity
     * @return
     */
    @Override
    public BaseResultVo edit(@Validated({EditCategory.class}) Category entity) throws Exception {
        String token = request.getHeader("token");
        String userId = cacheUtil.getUser(token).getUserId();
        String orgId = cacheUtil.getUser(token).getCompanys().get(0).getCompanyId();
        entity.setEuser(userId);
        entity.setEtime(DateUtil.now());
        entity.setOrgId1(orgId);
        Category category = service.edit(entity);
        return BaseResultVo.success("success", category.getId());
    }


    /**
     * 查看
     *
     * @param entity
     * @return
     */
    @Override
    public BaseResultVo view(@Validated({ViewCategory.class}) Category entity) throws Exception {
        Category category = service.view(entity);
        return BaseResultVo.success("success", category);
    }

    /**
     * 删除
     *
     * @param entity
     * @return
     */
    @Override
    public BaseResultVo del(@Validated({DelCategory.class}) Category entity) throws Exception {
        String token = request.getHeader("token");
        String userId = cacheUtil.getUser(token).getUserId();
        String orgId = cacheUtil.getUser(token).getCompanys().get(0).getCompanyId();
        entity.setEuser(userId);
        entity.setEtime(DateUtil.now());
        Category category = service.del(entity);
        return BaseResultVo.success("success", category.getId());
    }

    /**
     * 查询机构下可用仓库
     *
     * @param
     * @return
     */
    @Override
    public BaseResultVo getAvailableCategoryByOrgId() throws Exception {
        String token = request.getHeader("token");
        String userId = cacheUtil.getUser(token).getUserId();
        String orgId = cacheUtil.getUser(token).getCompanys().get(0).getCompanyId();
        List<Category> categoryList = service.getAvailableCategoryByOrgId(orgId);
        return BaseResultVo.success("success", categoryList);
    }

    /**
     * 查询用户权限下可用仓库
     *
     * @param
     * @return
     */
    @Override
    public BaseResultVo getAvailableCategoryByUserId() throws Exception {
        String token = request.getHeader("token");
        String userId = cacheUtil.getUser(token).getUserId();
        String orgId = cacheUtil.getUser(token).getCompanys().get(0).getCompanyId();
        List<Category> categoryList = service.getAvailableCategoryByUserId(userId,orgId);
        return BaseResultVo.success("success", categoryList);
    }

    /**
     * 列表查询
     *
     * @param params
     * @return
     * @throws Exception
     */
    @Override
    @ApiOperation(value = "列表查询", notes = "列表查询")
    public BaseResultVo getPages(PageParams<Category> params) throws Exception {
        String token = request.getHeader("token");
        String userId = cacheUtil.getUser(token).getUserId();
        String orgId = cacheUtil.getUser(token).getCompanys().get(0).getCompanyId();
        params.getParams().setOrgId(orgId);
        List<Category> categoryList = service.getPages(params);
        for (Category category : categoryList) {
            category.setOrgName(orgManagementMapper.selectByPrimaryKey(category.getOrgId()).getName());
            category.setOrgTreeCode(orgManagementMapper.selectByPrimaryKey(category.getOrgId()).getTreecode());
        }
        PageBean<Category> page = new PageBean<>(categoryList);
        return BaseResultVo.success(page);
    }

    /**
     * 导出
     *
     * @param companyId
     * @param response
     * @throws Exception
     */
    @Override
    public void export(String companyId, HttpServletResponse response) throws Exception {
        List<Category> list = service.getAllCategory(companyId);
        String fileName = "耗材仓库";
        ExcelUtils.exportExcel(list, Category.class, fileName, response);
    }


    @ApiOperation(value = "即时库存查询", notes = "即时库存查询", httpMethod = "POST")
    @Override
    public BaseResultVo<ReceiptStock> getStockList(@RequestBody PageParams<StockParams> params) {
        PageHelper.startPage(params.getCurrentPage(), params.getPerPageTotal());
        List<ReceiptStock> pageList = service.getStockList(params);
        PageBean<ReceiptStock> page = new PageBean<ReceiptStock>(pageList);
        return BaseResultVo.success(page);
    }

    /**
     * 即时库存导出
     *
     * @param
     * @param
     * @throws Exception
     */
    @Override
    public void Export(String userid, String orgid, String name, String ckid, HttpServletResponse response) throws Exception {
        StockParams params = new StockParams();
        params.setCkid(ckid);
        params.setOrgid(orgid);
        params.setName(name);
        params.setUserid(userid);
        List<ReceiptStock> list = service.Export(params);
        String fileName = "即时库存" + TimeTool.getTimeDate14();
        ExcelUtils.exportExcel(list, "即时库存", "即时库存", ReceiptStock.class, fileName, response);
    }

    @ApiOperation(value = "耗材领用查询", notes = "耗材领用查询", httpMethod = "POST")
    @Override
    public BaseResultVo<ReceiptMables> getMablesList(@RequestBody PageParams<MablesParams> params) {
        PageHelper.startPage(params.getCurrentPage(), params.getPerPageTotal());
        if (StrUtil.isNotBlank(params.getParams().getStartdate())) {
            byte[] space = new byte[]{(byte) 0xc2, (byte) 0xa0};
            String UTFSpace = null;
            try {
                UTFSpace = new String(space, "utf-8");
            } catch (Exception e) {
                log.error("", e);
            }
            // 这里的smsContent就是前端传过来的包含乱码的值。
            params.getParams().setStartdate(params.getParams().getStartdate().replace(UTFSpace, " "));
            params.getParams().setEnddate(params.getParams().getEnddate().replace(UTFSpace, " "));
        }
        List<ReceiptMables> pageList = service.getMablesList(params);
        PageBean<ReceiptMables> page = new PageBean<ReceiptMables>(pageList);
        return BaseResultVo.success(page);
    }

    /**
     * 耗材领用查询导出
     *
     * @param
     * @param
     * @throws Exception
     */
    @Override
    public void MablExport(String userid,String orgid,String squserid,String sqdeptid,String sqorgid,String startdate,String enddate,HttpServletResponse response) throws Exception {
        MablesParams params = new MablesParams();
        params.setSquserid(squserid);
        params.setSqdeptid(sqdeptid);
        params.setSqorgid(sqorgid);
        params.setStartdate(startdate);
        params.setEnddate(enddate);
        params.setOrgid(orgid);
        params.setUserid(userid);
        List<ReceiptMables> list = service.MablExport(params);
        String fileName = "耗材领用查询" + TimeTool.getTimeDate14();
        ExcelUtils.exportExcel(list, "耗材领用查询", "耗材领用查询", ReceiptMables.class, fileName, response);
    }




    @ApiOperation(value = "耗材领用表", notes = "耗材领用表", httpMethod = "POST")
    @Override
    public BaseResultVo<ReceiptConsume> getConsumeList(@RequestBody PageParams<ConsumeParams> params) {
        List<ReceiptConsume> pageList = service.getConsumeList(params);
        PageBean<ReceiptConsume> page = new PageBean<ReceiptConsume>(pageList);
        return BaseResultVo.success(page);
    }

    /**
     * 打印耗材领用查询
     */
    public void MablPrint(MablesParams mablesParams)throws IOException {
        ReceiptMables receiptMables = service.MablPrint(mablesParams);
        String title = "耗材领用";
        String sheetName = "耗材领用";
        String fileName = "耗材领用";
        //        创建HSSFWorkbook对象(excel的文档对象)
        HSSFWorkbook wb = new HSSFWorkbook();
        HSSFRow row = null;
        HSSFCell cell = null;
        int rownum = 0;
        // 建立新的sheet对象（excel的表单） 并设置sheet名字
        HSSFSheet sheet = wb.createSheet(sheetName);
        sheet.setDefaultColumnWidth(18);
        sheet.setColumnWidth(0, 256 * 6);
        sheet.setDefaultRowHeight((short) 512);
        // 在sheet里创建第一行，参数为行索引(excel的行)，可以是0～65535之间的任何一个
        row = sheet.createRow(rownum++);
        row.setHeight((short) 1000 );
        // 创建单元格（excel的单元格，参数为列索引，可以是0～255之间的任何一个
        cell = row.createCell(1);
        // 合并单元格CellRangeAddress构造参数依次表示起始行，截至行，起始列， 截至列
        sheet.addMergedRegion(new CellRangeAddress(0, 0, 1, 8));
        cell.setCellValue(title);
        cell.setCellStyle(ExcelStyle.styleTitle(wb));

        String[] row1 = {"耗材分类","耗材名称","领用单号","领用日期","领用量","金额"};
        List<String[]> rowList = new ArrayList<>();
        rowList.add(row1);

        for (String[] rows : rowList) {
            row = sheet.createRow(rownum++);
            for (int i = 0; i < rows.length; i++) {
                cell = row.createCell(i + 1);
                cell.setCellValue(rows[i]);
                if(rownum == 6){
                    cell.setCellStyle(ExcelStyle.styleNotBorder(wb, 3));
                    row.setHeight((short)700);
                } else if (rownum == 7){
                    cell.setCellStyle(ExcelStyle.styleCellName(wb));
                } else {
                    cell.setCellStyle(ExcelStyle.styleNotBorder(wb, 2));
                }

            }
        }

        //遍历数据
        int j =1;
        for(ReceiptCon receiptCon : receiptMables.getReceiptConList()){
            row = sheet.createRow(rownum++);
            String[] cells ={"",receiptCon.getFlname(),receiptCon.getHcname(),receiptCon.getNumber(),receiptCon.getDate(), String.valueOf(receiptCon.getLynum()),receiptCon.getPrice()};
            for (int i = 0; i < cells.length; i++) {
                cell = row.createCell(i + 1);
                if(i==0){
                    cell.setCellValue(j++);
                } else {
                    cell.setCellValue(cells[i]);
                }
                cell.setCellStyle(ExcelStyle.styleCellValue(wb));
            }
        }

        // 输出Excel文件
        OutputStream output = response.getOutputStream();
        response.reset();
        response.setHeader("Content-disposition","attachment; filename="+ URLEncoder.encode(fileName + ".xlsx", "UTF-8"));    //filename =  文件名
        response.setContentType("application/msexcel");
        wb.write(output);
        output.close();
    }
}

